//
//  UITextView+Emoticon.swift
//  SSEmoticon
//
//  Created by stevenSu on 15/8/6.
//  Copyright © 2015年 stevenSu. All rights reserved.
//

import UIKit

extension UITextView {
    var emoticonText: String {
        var strM = String()
        attributedText.enumerateAttributesInRange(NSMakeRange(0, attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dict, range, _) -> Void in
            
            if let emoticonAlignment = dict["NSAttachment"] as? SSEmoticonAttachment {
                strM += emoticonAlignment.chs ?? ""
            } else {
                let str = (self.attributedText.string as NSString).substringWithRange(range)
                strM += str
            }
        }
        return strM
    }
    
    func showSelectedEmoticon(emoticon: SSEmoticon) {
        if emoticon.isRemoveBtn {
            deleteBackward()
            return
        }
        
        if emoticon.emojiString != nil {
            insertText(emoticon.emojiString!)
        } else if emoticon.pngPath != nil {

            let attrStr = SSEmoticonAttachment.createAttrString(emoticon, font: font!)
            
            // 文本框属性字符串
            let attrText = attributedText
            // 可变属性字符串
            let text = NSMutableAttributedString(attributedString: attrText)
            // 插入
            text.replaceCharactersInRange(selectedRange, withAttributedString: attrStr)
            // 记录光标位置
            var range = selectedRange
            // 替换
            attributedText = text
            // 恢复光标位置
            range.location++
            selectedRange = range
            delegate?.textViewDidChange!(self)
        }
    }
}